import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';
import Validation from 'backbone-validation';
import FormBehavior from "../../base/behaviors/FormBehavior.js";

import InputWidget from '../../widgets/InputWidget.js';
import StatusHistoryView from '../../common/views/StatusHistoryView.js';
import _ from 'underscore';


var template = require("./templates/GeneralView.mustache");


const GeneralView = Mn.View.extend({
    /*
     * Wrapper around the component making part of the 'common'
     * invoice/estimation form, provide a main layout with regions for each
     * field
     */
    behaviors: [{
        behaviorClass: FormBehavior,
        errorMessage: "Vérifiez votre saisie"
    }],
    tagName: 'div',
    className: 'separate_block border_left_block',
    template: template,
    regions: {
        status_history: '.status_history',
        name: '.name',
        financial_year: '.financial_year',
    },
    modelEvents: {
        'validated:invalid': 'showErrors',
        'validated:valid': 'hideErrors',
    },
    childViewTriggers: {
        'change': 'data:modified',
        'finish': 'data:persist'
    },
    initialize(options) {
        this.section = options['section'];
        this.business_types_options = Radio.channel('config').request(
            'get:options', 'business_types'
        );
        var channel = Radio.channel('facade');
        this.listenTo(channel, 'bind:validation', this.bindValidation);
        this.listenTo(channel, 'unbind:validation', this.unbindValidation);
    },
    bindValidation() {
        Validation.bind(this);
    },
    unbindValidation() {
        Validation.unbind(this);
    },
    showErrors(model, errors) {
        this.$el.addClass('error');
    },
    hideErrors(model) {
        this.$el.removeClass('error');
    },
    templateContext() {
        let result = {};
        if (this.business_types_options.length > 1) {
            result['business_type'] = this.model.getBusinessType();
        }
        result['financial_year'] = 'financial_year' in this.section;
        return result;
    },
    showStatusHistory() {
        var collection = Radio.channel('facade').request(
            'get:collection', 'status_history'
        );
        var view = new StatusHistoryView({
            collection: collection
        });
        this.showChildView('status_history', view);
    },
    showName() {
        this.showChildView(
            'name',
            new InputWidget({
                title: "Nom du document",
                value: this.model.get('name'),
                field_name: 'name',
                required: true
            })
        );
    },

    onRender() {
        this.showStatusHistory();
        this.showName();
    }
});
export default GeneralView;